<?php

//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                                  |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                     |
// +------------------------------------------------------------------------+
// | Author: anguolei@clcw.com.cn                                           |
// +------------------------------------------------------------------------+
//
/**
 * 签约调度
 */

namespace AuctionBack\Controller;

use AuctionCore\AuctionOrder\AuOrderList as AuOrderList;
use AuctionCore\AuctionOrder\AuOrder;
use AuctionCore\AuctionOrder\Signature;
use AuctionCore\CarResource\Car;
use AuctionCore\CarOwner\Owner;
use AuctionCore\Account\Back\Employee;
use AuctionCore\Finance\Payment;
use AuctionCore\Other\Address;
use AuctionCore\CarDealer\AssetCenter;
use AuctionCore\Other\Channel;
use AuctionCore\Other\Inbox;
use AuctionCore\Finance\Collection;
use AuctionCore\ChangeOrder\ChangeOrder;
use AuctionCore\PurchaseOrder\PurchaseOrder;
use AuctionCore\Cashier\Payment as CashierPayment;
use AuctionBack\Logic\CarReportLogic;

class SignController extends BaseController
{

    public function __construct()
    {
        parent::__construct();
        $this->emp_id = $this->user_info['emp_id'];
    }

    /**
     * 签约调度页
     */
    public function index()
    {
        $this->display();
    }

    /**
     * 签约列表
     */
    public function getList()
    {
        $page = I("get.p", 1);
        $size = 10;
        $params = array();
        //待分配1,待签约2，跟踪中3，签约失败4，签约成功5
        $status = I("get.status/d");
        if ($status < 1) {
            $this->assign('errorMsg', "参数错误，请联系管理员");
            $this->display("Sign/error");
            exit;
        }
        $params['status'] = $status;
        if ($params['status'] == '3') {
            $params['sign_start_time'] = I("get.start_time", '');
            $params['sign_end_time'] = I("get.end_time", '');
        } elseif ($params['status'] == '2') {
            $params['sign_start_time'] = I("get.start_time", '');
            $params['sign_end_time'] = I("get.end_time", '');
        } elseif ($params['status'] == '1') {
            $params['sign_start_time'] = I("get.start_time", '');
            $params['sign_end_time'] = I("get.end_time", '');
        }

        $bc_city = I("get.bc_city");
        if ($bc_city) {
            $params['bc_city'] = $bc_city;
        } else {
            $params['bc_city'] = $this->user_info['bc_code'];;
        }

        $params['order_no'] = I("get.order_no", '');
        $params['area_id'] = I("get.area_id/d", 0);
        $params['emp_id'] = $this->user_info['emp_id'];
        //检查权限
        $rules = "QianYueChaKanSuoYou";
        $e = new Employee($this->user_info['username']);
        $params['auth'] = $e->check_auth($rules);
        //获取list
        $aol = new AuOrderList();
        // print_r($params);
        $result = $aol->sign_list($page, $size, $params);
        $Page = new \AuctionCore\Common\AjaxPage($result['total'], $size, "get_page");
        $Page->setConfig('theme', " %totalRow% %header% %nowPage%/%totalPage% 页 %first% %upPage% %prePage% %linkPage% %downPage% %nextPage% %end% %jumpform%");
        $show = $Page->show(); // 分页显示输出
        //模板赋值
        $this->assign('page', $show); // 赋值分页输出
        $this->assign('list', $result['list']);
        $this->assign("params", $params);
        $this->display("Sign/list");
    }


    /**
     * 成功或失败列表
     */
    public function resultList()
    {
        $page = I("get.p", 1);
        $size = 10;
        $status = I("get.status/d");
        $bc_city = I("get.bc_city");
        if ($bc_city) {
            $params['bc_city'] = $bc_city;
        } else {
            $params['bc_city'] = $this->user_info['bc_code'];;
        }
        $params['result'] = ($status == 6 || $status == 4) ? 1 : 3;
        $params['order_no'] = I("get.order_no", '');
        $params['status'] = $status;
        //检查权限
        $rules = "QianYueChaKanSuoYou";
        $e = new Employee($this->user_info['username']);
        $params['auth'] = $e->check_auth($rules);
        $sign = new Signature();
        $result = $sign->get_list($page, $size, $params);
        $total = $result['total'] > 0 ? $result['total'] : 0;
        $list = !empty($result['list']) ? $result['list'] : array();
        $Page = new \AuctionCore\Common\AjaxPage($total, $size, "get_page");
        $Page->setConfig('theme', " %totalRow% %header% %nowPage%/%totalPage% 页 %first% %upPage% %prePage% %linkPage% %downPage% %nextPage% %end% %jumpform%");
        $show = $Page->show(); // 分页显示输出
        //模板赋值
        $this->assign('page', $show); // 赋值分页输出
        $this->assign('list', $list);
        $this->assign("params", $params);
        $this->display("Sign/list");
    }

    /**
     * 分配交付顾问签约
     */
    public function dispatch()
    {
        $order_id = I("get.id/d");
        if ((int)$order_id < 1) {
            $this->helpJsRedirect("订单编号错误");
        }
        $o = new AuOrder($order_id);
        $order = $o->detail();
        $c = new Car($order['car_id']);
        $car = $c->detail();
        $co = new Owner($car['owner_id']);
        $owner = $co->detail();
        $owner['sign_reserve_time'] = transform_date($owner['sign_reserve_time'], 1);
        $result = $order['is_consult'] == 0 ? 1 : 4;
        $remark = $co->read_remark(['order_id' => $order_id, 'result' => $result]);
        //交付顾问
        $branch_id = $this->user_info['branch_id'];
        $delivery_advisor = C('DELIVERY_ADVISOR');
        $all_depart = \AuctionCore\Account\Back\Employee::get_branch_depart($delivery_advisor[0], $branch_id);
        $all_depart = explode(',', $all_depart['all_depart']);
        if ($branch_id == 0) {
            $branch_id = 1;
        }
        $new_arr[] = M('depart')->field('id,pid,name')->where(array('id' => $branch_id))->find();
        $departs = \AuctionCore\Account\Back\Department::get_father_depart($all_depart, $branch_id, $new_arr);
        // $checkers = Employee::get_emp_by_group_or_store($delivery_advisor[0],0,$branch_id);
        $this->assign('departs', $departs);
        $addr = new Address();
        $location_area = $addr->get_name_by_code($car['location_area']);
        $province = $addr->get_name_by_code($owner['sign_reserve_province']);
        $city = $addr->get_name_by_code($owner['sign_reserve_city']);
        $area = $addr->get_name_by_code($owner['sign_reserve_area']);
        $owner['address'] = $province . " " . $city . " " . $area . " " . $owner['sign_reserve_address'];
        $store = new \AuctionCore\Other\Store();
        $address = $store->detail(array('store_id' => $owner['sign_reserve_store']));
        $terminal = $address['store_name'];
        $this->assign('terminal', $terminal);
        $this->assign('remark', $remark);
        $this->assign('order', $order);
        $this->assign('car', $car);
        $this->assign('owner', $owner);
        $this->assign('location_area', $location_area);
        // $this->assign('checkers', $checkers);
        $this->display();
    }

    //根据部门id找到对应角色人员
    public function get_delivery()
    {
        $depart_id = I("request.depart_id");
        if ($depart_id < 1) {
            $this->helpJsonResult(500, '部门id不能为空');
        }
        $delivery_advisor = C('DELIVERY_ADVISOR');
        $checkers = \AuctionCore\Account\Back\Employee::get_depart_emp($delivery_advisor[0], $depart_id);
        // var_dump($checkers);
        if (empty($checkers)) {
            $this->helpJsonResult(500, 'empty');
        }
        $this->helpJsonResult(200, 'checker list', $checkers);
    }

    /**
     * 保存分配信息
     */
    public function saveDisPatch()
    {
        $order_id = I("post.order_id/d");
        if ((int)$order_id < 1) {
            $this->helpJsonResult(400, "订单编号错误");
        }
        $o = new AuOrder($order_id);
        $order = $o->detail();
        if ($order['is_lock'] == 1) {
            $this->helpJsonResult(500, "拍单已锁定");
        }
        $owner_id = I("post.owner_id/d");
        if ((int)$owner_id < 1) {
            $this->helpJsonResult(400, "参数错误");
        }
        $deliver_id = I("post.deliver_id/d");
        if ((int)$deliver_id < 1) {
            $this->helpJsonResult(400, "请选择顾问信息");
        }
        $data['deliver_id'] = (int)$deliver_id;
        $data['sign_reserve_remark'] = I("post.sign_reserve_remark", '');
        //$data['business_status'] = 11; //修改线索表业务状态为分配待签约
        $co = new Owner($owner_id);
        $result = $co->update($data);
        if (!$result) {
            $this->helpJsonResult(500, "服务器错误，稍后再试");
        }

        /**
         * 记录车辆跟踪日志
         */
        $car_action_data = array(
            'action_name' => "签约分配成功",
            'emp_id' => $this->emp_id
        );
        \AuctionCore\CarResource\Car::add_car_trace_log($order['car_id'], $car_action_data);
        /**
         * 记录拍品跟踪日志
         */
        $order_action_data = array(
            'action_name' => "签约分配成功",
            'emp_id' => $this->emp_id
        );
        \AuctionCore\AuctionOrder\AuOrder::add_order_trace_log($order['order_id'], $order_action_data);

        $this->helpJsonResult(200, "分配成功");
    }

    /**
     * 签约列表页面
     */
    public function signing()
    {
        $this->display();
    }

    /**
     * 签约
     */
    public function signature()
    {
        $order_id = I("get.id/d");
        $status = I("get.status/d");
        if ($order_id < 1) {
            $this->helpJsRedirect("拍单信息错误");
        }
        $o = new AuOrder($order_id);
        $order = $o->detail();
        $owner_confirm_detail = $o->owner_confirm_detail();
        //获取车辆信息
        $c = new Car($order['car_id']);
        $car = $c->detail();
        $car['transfer_limit_str'] = C('TRANSFER_LIMIT.' . $car['transfer_limit']);

        $cm = new \AuctionCore\CarResource\CarModel();
        $brand = $cm->get_model_by_id($car['brand_id'], 'brand');
        $series = $cm->get_model_by_id($car['series_id'], 'series');
        $model = $cm->get_model_by_id($car['model_id']);
        $car['model'] = $brand['name'] . ' ' . $series['name'] . ' ' . $model['name'];
        //获取车主信息
        $co = new Owner($car['owner_id']);
        $owner = $co->detail();

        $owner['sign_date'] = date('Y-m-d', strtotime($owner['sign_date']));
        $owner['owner_type_name'] = C('OWNER_TYPE_NAME')[$owner['owner_type']];
        if (($status == 2 || $status == 3) && $owner['deliver_id'] != $this->user_info['emp_id']) {
            $this->helpJsRedirect("非法操作");
        }

        /* if (($status == 2 || $status == 3)) {
             $this->helpJsRedirect("非法操作");
         }*/
        //获取渠道来源信息
        $car['channel_str'] = Channel::get_full_name_by_id($owner['comefrom']);
        //所在地
        $addr = new Address();
        $location_area = $addr->get_name_by_code($car['location_area']);
        //获取地址信息
        if ($owner['sign_service_method'] == 3) { //到店
            $store = new \AuctionCore\Other\Store();
            $address = $store->detail(array('store_id' => $owner['sign_reserve_store']));
            $terminal = $address['store_name'];
        } else {
            $province = $addr->get_name_by_code($owner['sign_reserve_province']);
            $city = $addr->get_name_by_code($owner['sign_reserve_city']);
            $area = $addr->get_name_by_code($owner['sign_reserve_area']);
            $owner['address'] = $province . " " . $city . " " . $area . " " . $owner['sign_reserve_address'];
        }
        $deliver = Employee::user_info_id($owner['deliver_id']);
        $owner['deliver'] = $deliver['real_name'];
        $car['reg_city'] = $addr->get_name_by_code($car['reg_city']); //车辆注册地
        $car['pointer_mileage'] = formatMileage($car['pointer_mileage']);
        //跟踪日志
        $trace_log = Signature::get_trace_log($order_id);
        //签约日志
        if ($status == 5) {
            $remark_result = 3;
        } elseif ($status == 4) {
            $remark_result = 1;
        }
        $log = AuOrder::get_signature_log(array('owner_id' => $owner['owner_id'], 'result' => $remark_result));
        //车主确定日志
        if ($owner_confirm_detail['status'] >= '7' && $owner_confirm_detail['status'] != '6'
            && $owner_confirm_detail['status'] != '12' && $owner_confirm_detail['owner_confirm_service_id'] > '0' &&
            $owner_confirm_detail['is_consult'] == 0
        ) {
            $owner_remark_result = 1;
        } elseif ($owner_confirm_detail['status'] >= '7' &&
            $owner_confirm_detail['status'] != '12' &&
            $owner_confirm_detail['owner_confirm_service_id'] > 0 &&
            $owner_confirm_detail['is_consult'] == 1
        ) {
            $owner_remark_result = 4;
        }
        $remark = $co->read_remark(array('order_id' => $order_id, 'result' => $owner_remark_result));
        //echo M()->getLastSql();

        $this->assign('terminal', $terminal);
        $this->assign('order', $order);
        $this->assign('detail', $owner_confirm_detail);
        $this->assign('remark', $remark);
        $this->assign('trace_log', $trace_log);
        $this->assign('car', $car);
        $this->assign('owner', $owner);
        $this->assign('log', $log);
        $this->assign('status', $status);
        $this->assign('location_area', $location_area);
        $this->assign('trans_procs', C("TRANSFER_PROCEDURE"));
        $this->display();
    }

    /**
     * 确认签约成功
     */
    public function signSuccess()
    {
        $order_id = I("post.order_id/d");
        if ($order_id < 1) {
            $this->helpJsonResult(408, "订单ID错误");
        }
        $car_id = I("post.car_id/d");
        if ($car_id < 1) {
            $this->helpJsonResult(408, "车辆ID错误");
        }
        $owner_id = I("post.owner_id/d");
        if ($owner_id < 1) {
            $this->helpJsonResult(408, "车主ID错误");
        }
        $co = new Owner($owner_id);
        $ownerInfo = $co->detail();
        //检查过户手续
        $transfer_str = I('post.transfer_proc');
        $transfer_arr = explode(',', $transfer_str);
        $transfers = C("TRANSFER_PROCEDURE");
        $difference = array_diff($transfers, $transfer_arr);
        $transfer_procedure = implode(",", array_keys($transfers));
        if (!empty($difference)) {
            $this->helpJsonResult(411, "请确认过户手续是否齐全");
        }
        //检查年检情况
        $mot = I('post.MOT');
        if (empty($mot)) {
            $this->helpJsonResult(416, "请选择年检情况");
        }
        $mot_val = array_keys(C("MOT"), $mot);
        //检查违章情况
        $peccancy = I('post.peccancy');
        if (empty($peccancy)) {
            $this->helpJsonResult(417, "请选择违章情况");
        }
        $peccancy_val = array_keys(C("PECCANCY"), $peccancy);

        //检查三证合一情况
        $three_in_one = I('post.three_in_one');
        if (empty($three_in_one)) {
            $this->helpJsonResult(419, "请选择三证情况");
        }
        $three_in_one_val = array_keys(C("THREE_IN_ONE"), $three_in_one);

        $payee_name = I('post.payee_name', '');
        if (empty($payee_name)) {
            $this->helpJsonResult(412, "请输入收款人");
        }
        $deposit_bank = I('post.deposit_bank', '');
        if (empty($deposit_bank)) {
            $this->helpJsonResult(413, "请输入开户行");
        }
        $payee_account = I('post.payee_account', '');
        if (empty($payee_account)) {
            $this->helpJsonResult(414, "请输入银行账号");
        }
        $sign_time = I("post.sign_time");
        if (empty($sign_time)) {
            $this->helpJsonResult(415, "请选择签约日期");
        }
        $o = new AuOrder($order_id);
        $order = $o->detail();
        if (empty($order)) {
            $this->helpJsonResult(400, "未找到拍单信息");
        }
        if ($order['is_lock'] == 1) {
            $this->helpJsonResult(500, "拍单已锁定");
        }
        $car = new Car($car_id);
        $car_detail = $car->detail();
        //记录签约记录数据au_signature_log
        $signature_log['payee_name'] = $payee_name;
        $signature_log['deposit_bank'] = $deposit_bank;
        $signature_log['delivery_id'] = $ownerInfo['deliver_id'];
        $signature_log['payee_account'] = $payee_account;
        $signature_log['sign_time'] = $sign_time;
        $signature_log['transfer_proc'] = $transfer_procedure;
        $signature_log['remark'] = I('post.succes_remark', '');
        $signature_log['result'] = 1;
        $signature_log['emp_id'] = $this->user_info['emp_id'];
        $signature_log['owner_id'] = $owner_id;

        $owner_data = array(
            "sign_date" => $sign_time,
            "sign_remark" => I('post.succes_remark', '')
        );

        $final_price = Payment::owner_final_price($order_id);
        $data = array(); //拍单表数据
        $car_data = array(); //车源表数据
        $car_data['mot'] = $mot_val[0]; //
        $car_data['peccancy'] = $peccancy_val[0];
        $car_data['three_in_one'] = $three_in_one_val[0];
        //启动事务
        M()->startTrans();

        //获取车商交付模式：1、先付款后验车 2、先验车后付款
        $pay_mode = $o->get_dealer_pay_mode();
        //自收车辆则不走验车,仍添加付款记录
        /*$dealer = new \AuctionCore\CarDealer\Dealer($order['success_dealer_id']);
        $dealer_info = $dealer->get_dealer_info_by_dealer_id($order['success_dealer_id']);
        if ($dealer_info['dealer_type'] == 1) {*/
        if ($car_detail['is_self_receive'] == 1) {
            $data = [
                'car_id' => $order['car_id'],
                'order_id' => $order['order_id'],
                'compensate_type' => 1,
                'self_type' => 1
            ];
            $self_receive_car = new \AuctionCore\CarResource\SelfReceiveCar();
            $self_receive_car_ret = $self_receive_car->add_self_receive_car($data);
            if (!$self_receive_car_ret) {
                M()->rollback();
                $this->helpJsonResult(500, "操作失败");
            }
            $car_data['self_receive_price'] = $final_price;
            $data['status'] = 12;
            $data['fail_type'] = 10; //自收完成导致的拍单失败

            //自收车辆签约完成到自收车辆后解冻保证金
            \AuctionCore\CarDealer\AssetCenter::free_all($order['order_id']);
        } else {
            $collect_ret = Collection::add(['order_id' => $order_id]);
            if (!$collect_ret) {
                M()->rollback();
                $this->helpJsonResult(500, "操作失败");
            }
            // }
            $data['status'] = 8;
        }

        $purchaseOrderArr = [
            'order_id' => $order_id,
            'order_no' => $order['order_no'],
            'car_id' => $car_id,
            'sid' => $car_detail['sid'],
            'amount' => $final_price,
            'emp_id' => $this->emp_id,
            'type' => $car_detail['is_self_receive'] ? '2' : '1', //判断是否自收车
            'status' => '1',
            'pay_status' => $three_in_one_val[0] == '1' ? 1 :2 ,
            'createtime' => date('Y-m-d H:i:s', time()),
        ];

        $res5 = $this->addPurchaseOrder($purchaseOrderArr); //添加采购单
        if (!$res5) {
            M()->rollback();
            $this->helpJsonResult(500, "添加采购单信息失败");
        }
        if ($three_in_one_val[0] == '1') {  //三证合一
            $data['first_money'] = $final_price / 2;
            $car_data['pay_status'] = 1; //更改车辆付款状态为代付首款
            $res = Payment::create($car_id, $order_id, 1); //添加付首款信息
            if (!$res) {
                M()->rollback();
                $this->helpJsonResult(500, "添加付款信息失败");
            }

            $paymentData['amount'] = $data['first_money']; //个人车源 50%首款
            $paymentData['pay_type'] = 2; // 个人车源 付50%
            $paymentData['bank_name'] = $deposit_bank; //收款银行
            $paymentData['card_no'] = $payee_account; // 收款账号
            $paymentData['account_name'] = $payee_name; //收款人姓名

	        $carReport = new CarReportLogic($car_id);
	        $branchId = $carReport->getBranchId();
	        $paymentData['branch_id'] = $branchId;
            $res6 = $this->generatorPayment($paymentData);//添加付款单
            if (!$res6) {
                M()->rollback();
                $this->helpJsonResult(500, "添加付款单信息失败");
            }
            $res7 = $this->addPaymentRelation($res5, $res6, $paymentData['pay_type']);
            if (!$res7) {
                M()->rollback();
                $this->helpJsonResult(500, "添加付款单采购单关系失败");
            }

        } else {
            $data['first_money'] = 0;
            $data['first_pay_status'] = 1;
            $car_data['pay_status'] = 2;    //更改车辆代已付首款
        }

        $data['tail_money'] = $final_price - $data['first_money'];
        $result = $o->update($data); //更新拍单表
        $car_result = $car->update($car_data); //更新车源表
        $owner_result = $co->update($owner_data); //更新车主表
        //记录签约日志
        $log_result = $o->set_trace_log('signature_log', $signature_log);

        if (!$result || !$log_result || !$car_result || !$owner_result) {
            M()->rollback();
            $msg = '确认失败或已确认,数据未更新。';
            $this->helpJsonResult(500, $msg);
        }
        M()->commit();
        //发送消息
        $uid = $o->get_uid_by_order();
        $car_name = $car->get_car_name();
        $content = "【 " . $car_name . " 】拍单编号：" . $order['order_no'] . "，确认成功。敬请到店验车、付款和提交过户资料。";
        Inbox::sendMessage($uid, '车辆待付款', $content);

        //记录员工操作日志
        $log = array('emp_id' => $this->user_info['emp_id'], 'order_id' => $order_id, 'car_id' => $car_id, 'owner_id' => $owner_id, 'action' => '签约,msg:确认签约成功');
        \AuctionCore\System\SystemLog::add($log);

        /**
         * 记录车辆跟踪日志
         */
        $car_action_data = array(
            'action_name' => "签约成功",
            'emp_id' => $this->emp_id
        );
        \AuctionCore\CarResource\Car::add_car_trace_log($car_id, $car_action_data);
        /**
         * 记录拍品跟踪日志
         */
        $order_action_data = array(
            'action_name' => "签约成功",
            'emp_id' => $this->emp_id
        );
        \AuctionCore\AuctionOrder\AuOrder::add_order_trace_log($order_id, $order_action_data);

        $this->helpJsonResult(200, "确认成功");
    }


    /**
     * 添加采购单
     *
     * @param array $data 采购单数据
     * @return mixed 返回添加结果
     */
    public function addPurchaseOrder($data)
    {
        $obj = new PurchaseOrder();
        $purchaseOrderType = $data['type'];
        $data['purchase_order_nu'] = $obj->generatePurchaseOrderNu($purchaseOrderType);
        return $obj->add($data);
    }


    /**
     *  添加付款单
     *
     * @param int $paymentData 付款单信息
     * @return mixed
     */
    public function generatorPayment($paymentData)
    {
        $paymentData['pay_way'] = 2;// 转账
        $paymentData['create_time'] = date('Y-m-d H:i:s');//创建时间
        $result = CashierPayment::add($paymentData);
        return $result;
    }

    /**
     * 添加采购单付款关系数据
     *
     * @param int $purchaseOrderId 采购单编号
     * @param int $paymentId 付款单编号
     * @param int $paymentType 付款类型
     * @return mixed
     */
    public function addPaymentRelation($purchaseOrderId, $paymentId, $paymentType)
    {
        $purchaseOrder = new PurchaseOrder();
        return $purchaseOrder->addPaymentAndPurchaseOrderRelation($purchaseOrderId, $paymentId, $paymentType);
    }

    /**
     * 签约失败
     */
    public function signFaild()
    {
        $order_id = I("post.order_id/d");
        if ($order_id < 1) {
            $this->helpJsonResult(408, "订单ID错误");
        }
        $car_id = I("post.car_id/d");
        if ($car_id < 1) {
            $this->helpJsonResult(408, "汽车ID错误");
        }
        $owner_id = I("post.owner_id/d");
        if ($owner_id < 1) {
            $this->helpJsonResult(408, "车主ID错误");
        }
        $sign_remark = I("post.faild_remark/s", '');
        if (empty($sign_remark)) {
            $this->helpJsonResult(400, "失败原因不能为空");
        }
        $signature_log['owner_id'] = $owner_id;
        $signature_log['result'] = 3;
        $signature_log['remark'] = $sign_remark;
        $signature_log['emp_id'] = $this->user_info['emp_id'];
        $data = array("status" => 12, "fail_type" => 3, "remark_fail" => $sign_remark);
        $o = new AuOrder($order_id);
        $order = $o->detail();
        if ($order['is_lock'] == 1) {
            $this->helpJsonResult(500, "拍单已锁定");
        }
        //启动事务
        M()->startTrans();
        $result = $o->update($data);
        $c = new Car($car_id);
        $car_result = $c->update(['car_status' => 8]);
        //记录签约日志
        $log_result = $o->set_trace_log('signature_log', $signature_log);
        if (!$result || !$car_result || !$log_result) {
            M()->rollback();
            $msg = '确认失败或已确认,数据未更新。';
            $this->helpJsonResult(500, $msg);
        }
        M()->commit();
        AssetCenter::free_all($order_id); //签约失败 解冻保证金
        //记录员工操作日志
        $log = array('emp_id' => $this->emp_id, 'order_id' => $order_id, 'car_id' => $car_id, 'owner_id' => $owner_id, 'action' => '签约,msg:确认签约失败');
        \AuctionCore\System\SystemLog::add($log);

        /**
         * 记录车辆跟踪日志
         */
        $car_action_data = array(
            'action_name' => "签约失败",
            'emp_id' => $this->emp_id
        );
        \AuctionCore\CarResource\Car::add_car_trace_log($car_id, $car_action_data);
        /**
         * 记录拍品跟踪日志
         */
        $order_action_data = array(
            'action_name' => "签约失败",
            'emp_id' => $this->emp_id
        );
        \AuctionCore\AuctionOrder\AuOrder::add_order_trace_log($order_id, $order_action_data);

        $this->helpJsonResult(200, "确认成功");
    }

    /**
     * 签约跟踪
     */
    public function signTrace()
    {
        $order_id = I("post.order_id/d");
        if ($order_id < 1) {
            $this->helpJsonResult(411, "订单ID错误");
        }
        $car_id = I("post.car_id/d");
        if ($car_id < 1) {
            $this->helpJsonResult(412, "汽车ID错误");
        }
        $owner_id = I("post.owner_id/d");
        if ($owner_id < 1) {
            $this->helpJsonResult(413, "车主ID错误");
        }
        $trace_remark = I("post.trace_remark");
        if (empty($trace_remark)) {
            $this->helpJsonResult(414, '请填写跟踪原因');
        }
        $next_trace_time = I("post.next_trace_time");
        if (empty($next_trace_time)) {
            $this->helpJsonResult(417, "请选择下次跟踪时间");
        }
        $signature_log['owner_id'] = $owner_id;
        $signature_log['result'] = 2;
        $signature_log['next_trace_time'] = $next_trace_time;
        $signature_log['remark'] = $trace_remark;
        $signature_log['emp_id'] = $this->user_info['emp_id'];

        $data = array('is_sign_tracing' => 1);
        $o = new AuOrder($order_id);
        $order = $o->detail();
        if ($order['is_lock'] == 1) {
            $this->helpJsonResult(500, "拍单已锁定");
        }
        //启动事务
        M()->startTrans();
        $result = $o->update($data);
        //记录签约日志
        $log_result = $o->set_trace_log('signature_log', $signature_log);
        if (!$result || !$log_result) {
            M()->rollback();
            $msg = '确认失败或已确认,数据未更新。';
            $this->helpJsonResult(500, $msg);
        }
        M()->commit();
        //记录员工操作日志
        $log = array('emp_id' => $this->emp_id, 'order_id' => $order_id, 'car_id' => $car_id, 'owner_id' => $owner_id, 'action' => '签约,msg:跟踪中');
        \AuctionCore\System\SystemLog::add($log);

        /**
         * 记录车辆跟踪日志
         */
        $car_action_data = array(
            'action_name' => "签约跟踪",
            'emp_id' => $this->emp_id
        );
        \AuctionCore\CarResource\Car::add_car_trace_log($car_id, $car_action_data);
        /**
         * 记录拍品跟踪日志
         */
        $order_action_data = array(
            'action_name' => "签约跟踪",
            'emp_id' => $this->emp_id
        );
        \AuctionCore\AuctionOrder\AuOrder::add_order_trace_log($order_id, $order_action_data);


        $this->helpJsonResult(200, "跟踪成功");
    }

    //查看签约信息
    public function signInfo()
    {

    }

    //通过门店获取交付顾问
    public function getDeliver()
    {
        $store_id = I("get.store_id/d", 0);
        if ($store_id < 1) {
            $this->helpJsonResult(200, '门店信息错误');
        }
        //
        $checkers = Employee::get_emp_by_group_or_store(387, $store_id);
        if (empty($checkers)) {
            $this->helpJsonResult(500, 'empty');
        }
        $this->helpJsonResult(200, 'empty', $checkers);
    }

    private function record_log($order_id, $car_id, $action)
    {
        //记录员工操作日志
        $log = [
            'emp_id' => $this->emp_id,
            'order_id' => $order_id,
            'car_id' => $car_id,
            'owner_id' => 0,
            'action' => $action
        ];
        \AuctionCore\System\SystemLog::add($log);

        /**
         * 记录车辆跟踪日志
         */
        $car_action_data = array(
            'action_name' => $action,
            'emp_id' => $this->emp_id
        );
        \AuctionCore\CarResource\Car::add_car_trace_log($car_id, $car_action_data);

        /**
         * 记录拍品跟踪日志
         */
        $order_action_data = array(
            'action_name' => $action,
            'emp_id' => $this->emp_id
        );
        \AuctionCore\AuctionOrder\AuOrder::add_order_trace_log($order_id, $order_action_data);
    }

    //违约
    public function violate()
    {
        $order_id = I("post.order_id/d", 0);
        if ($order_id < 1) {
            $this->helpJsonResult(400, "参数错误");
        }
        $o = new AuOrder($order_id);
        $orderInfo = $o->detail();
        if ($orderInfo['is_lock'] == 1) {
            $this->helpJsonResult(400, "拍单已锁定");
        }
        $poInfo = $o->getPurchaseByOrderId();
        $c = new Car($orderInfo['car_id']);
        $carInfo = $c->detail();
        $car_plate_number = C('PLATE_PREFIX')[$carInfo['plate_prefix']] . $carInfo['plate_suffix'];
        $data = [];
        $data['order_id'] = $order_id;
        $data['order_no'] = $orderInfo['order_no'];
        $data['po_id'] = $poInfo['id'];
        $data['po_no'] = $poInfo['purchase_order_nu'];
        $data['car_plate_number'] = $car_plate_number;
        $data['order_status'] = $orderInfo['status'];
        $data['source'] = 3;
        $data['originator'] = $this->emp_id;
        $res = ChangeOrder::CreateChangeOrder($data);
        if (!$res) {
            $this->helpJsonResult(400, '处理失败');
        } else {
            $this->record_log($order_id, $orderInfo['car_id'], "签约发起违约");
            $this->helpJsonResult(200, '处理成功');
        }
    }
}
